package com.medic.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.medic.annotation.LoginValidate;
import com.medic.entity.Admin;
import com.medic.util.CacheUtil;
import com.medic.util.StringUtil;

public class WebLoginValidateInterceptor extends HandlerInterceptorAdapter {

	private final String adminKey = "admin";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		boolean result = false;
		if (handler instanceof HandlerMethod) {
			HandlerMethod method = (HandlerMethod) handler;
			LoginValidate annotation = method.getMethod().getAnnotation(LoginValidate.class);
			if (annotation == null || annotation.needLogin()) {
				Admin admin = (Admin) request.getSession().getAttribute(adminKey);
				if (admin != null) {
					result = true;
				} else {
					response.sendRedirect(CacheUtil.getConfig().getProperty(StringUtil.ROOT_DIRECTORY)+"web/admin/login");
				}
			} else {
				
				result = true;
			}
		}
		return result;
	}

}
